package com.hanlin.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanlin.backend.common.entity.HlUserRole;
import com.hanlin.backend.mapper.HlUserRoleMapper;
import com.hanlin.backend.service.HlUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户与角色中间表 服务实现类
 * </p>
 *
 * @author hl.yuan
 * @since 2021-01-06
 */
@Service
@Slf4j
public class HlUserRoleServiceImpl extends ServiceImpl<HlUserRoleMapper, HlUserRole> implements HlUserRoleService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserRole(List<Integer> roles, Integer userId) {
        if (roles == null || userId == null) {
            log.info("角色或者userID为空，不进行保存【roles:{}，userID:{}】", roles, userId);
            return;
        }
        // 删除用户与角色的中间表
        QueryWrapper<HlUserRole> wrapper = new QueryWrapper();
        wrapper.eq("user_id", userId);
        this.remove(wrapper);
        List<HlUserRole> userRoleList = new ArrayList<>();
        // 添加用户与角色的中间表
        for (Integer role : roles) {
            HlUserRole userRole = new HlUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(role);
            userRoleList.add(userRole);
        }
        // 批量保存
        saveBatch(userRoleList);

    }
}
